// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System.Globalization;
using System.Text;

namespace SnapObjects.Data.MySql
{
    internal class MySqlUpdateSqlGenerator : UpdateSqlGenerator
    {
        public MySqlUpdateSqlGenerator(MySqlGenerationHelper mySqlSqlGenerationHelper) :
            base(mySqlSqlGenerationHelper)
        {
        }

        public StringBuilder AppendSqlTail(StringBuilder sql)
        {
            return sql.Append("select row_count();");
        }

        protected override ResultSetMapping AppendSelectAffectedCountSql(StringBuilder sqlStringBuilder, string name, string schema, int sqlPosition)
        {
            sqlStringBuilder
                .Append("SELECT row_count()")
                .AppendLine(this.SqlGenerationHelper.StatementTerminator)
                .AppendLine();

            return ResultSetMapping.RowCountAndLastInResultSet;
        }


        public override void AppendBatchHeader(StringBuilder sqlStringBuilder)
        {
            sqlStringBuilder
                .Append("SET NOCOUNT ON")
                .Append(this.SqlGenerationHelper.StatementTerminator).AppendLine();
        }

        protected override void AppendIdentityWhereCondition(StringBuilder sqlStringBuilder, ColumnModification columnModification)
        {
            sqlStringBuilder.AppendFormat("{0}=LAST_INSERT_ID()", this.SqlGenerationHelper.DelimitIdentifier(columnModification.MappedColumn));
        }

        protected override void AppendRowsAffectedWhereCondition(StringBuilder sqlStringBuilder, int expectedRowsAffected)
        {
            sqlStringBuilder
                .Append("ROW_COUNT() = ")
                .Append(expectedRowsAffected.ToString(CultureInfo.InvariantCulture));
        }
    }
}
